package com.ligq.h265ttoupinreceive

import android.media.MediaCodec
import android.media.MediaFormat
import android.util.Log
import android.view.Surface

class H264Player(surface: Surface) : SocketLive.SocketCallBack {
    private var mediaCodec: MediaCodec? = null
    private val width = 1080
    private val height = 2400

    init {
        try {
            mediaCodec = MediaCodec.createDecoderByType(MediaFormat.MIMETYPE_VIDEO_AVC)
            val format =
                MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height)
            format.setInteger(MediaFormat.KEY_BIT_RATE, width * height)
            format.setInteger(MediaFormat.KEY_FRAME_RATE, 20)
            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 20)
            mediaCodec?.configure(
                format,
                surface,
                null, 0
            )
            mediaCodec?.start()
        } catch (e: Exception) {
            Log.e(TAG, ": ", e)
        }

    }

    override fun callback(bytes: ByteArray) {
        val inputIndex = mediaCodec!!.dequeueInputBuffer(10000)
        if (inputIndex >= 0) {
            val inputBuffer = mediaCodec!!.getInputBuffer(inputIndex)
            inputBuffer?.run {
                clear()
                put(bytes)
            }
            mediaCodec?.queueInputBuffer(inputIndex, 0, bytes.size, System.currentTimeMillis(), 0)
        }

        val bufferInfo = MediaCodec.BufferInfo()
        var outIndex = mediaCodec!!.dequeueOutputBuffer(bufferInfo, 10000)
        //有些情况下数据并不能一次性解析完成，分包进行，所以需要用循环来解析
        while (outIndex >= 0) {
            mediaCodec!!.releaseOutputBuffer(outIndex, true)
            outIndex = mediaCodec!!.dequeueOutputBuffer(bufferInfo, 10000)
        }
    }
}